package com.ruoyi.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ImgUploadUtil {

    private static final Logger logger = LoggerFactory.getLogger(ImgUploadUtil.class);



    /**
     * 上传头像等图片到linux服务器
     */
    public static  String uploadProfilePhoto(MultipartFile image,String serverPath) {
        String path = null;

        if (image != null) {
            String filename = image.getOriginalFilename();
            try {
                //上传路径
                File directory = new File(serverPath);
                String paths = directory.getCanonicalPath();
                File file = new File(paths);
                if (!file.exists()) {
                    file.mkdirs();
                }
                //图片命名添加时间戳，防止图片重名
                /*SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
                String date = dateFormat.format(new Date());*/

                FileOutputStream outputStream = new FileOutputStream(serverPath + "/" + filename);
                outputStream.write(image.getBytes());
                outputStream.flush();
                outputStream.close();

                //获取服务器IP
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest httpServletRequest = requestAttributes.getRequest();
                String localAddr = httpServletRequest.getServerName();
                //获取端口号
                int serverPort = httpServletRequest.getServerPort();
                //腾讯云服务器
                if ("http".equals(httpServletRequest.getScheme())) {
                    path = "http://" + localAddr + ":" + serverPort + "/api/images/" + filename;
                }
                if ("https".equals(httpServletRequest.getScheme())) {
                    path = "https://" + localAddr + ":" + serverPort + "/api/images/" + filename;
                }

            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }

        return path;
    }

}
